﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Threading;
using unTroublemaker;

namespace unTroublemakerUI
{
    public partial class App
    {
        public App()
        {
            Dispatcher.UnhandledException += HandleCrash;
            AppDomain.CurrentDomain.UnhandledException += HandleCrash;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            DispatcherHelper.Initialize();
        }

        private void HandleCrash(object sender, UnhandledExceptionEventArgs e)
        {
            LogCrash((Exception)e.ExceptionObject);
        }

        private void HandleCrash(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogCrash(e.Exception);

#if DEBUG
#else
            e.Handled = true;
#endif
        }

        private void LogCrash(Exception exception)
        {
            var tag = "Unhandled exception occured at " + DateTime.Now.ToShortDateString() + " " +
                         DateTime.Now.ToShortTimeString() + ":\r\n";

            var path = Path.GetFullPath("Crash.log");
            File.WriteAllText(path, tag + exception.Format());
            
#if DEBUG
            Process.Start(path);
#else
            MessageBox.Show(
                "The application suffered an unhandled exception, the problem has been logged to:\r\n" + path,
                "Unhandled exception", MessageBoxButton.OK, MessageBoxImage.Error);
#endif
        }

        private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogCrash(e.Exception);
        }
    }
}
